package mina

import (
	"bgs/util"
	"context"
	"encoding/json"
	"fmt"
	"time"
)

type Token struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int32  `json:"expires_in"`
	Errcode     int    `json:"errcode"`
	Errmsg      string `json:"errmsg"`
}

// GetAccessToken 小程序获取accessToken
func (s *MinaServiceImp) GetAccessToken(ctx context.Context) (accessToken string, err error) {
	slog := util.NewContextLogger(ctx, s.slog)
	slog.Infof("获取小程序accessToken")

	accessToken = s.cacher.FetchMinaAccessToken()

	if accessToken == "" {
		apiUrl := s.getURL("/token")
		param := map[string]interface{}{
			"appid":      s.wechatVars.MinaAppID,
			"secret":     s.wechatVars.MinaSecret,
			"grant_type": "client_credential",
		}
		body, reqErr := util.GetRequest().Send(ctx, "GET", apiUrl, param, nil, 2)
		if reqErr != nil {
			err = reqErr
			return
		}
	
		tokenPtr := &Token{}
		if err = json.Unmarshal(body, tokenPtr); err != nil {
			return
		}
		if tokenPtr.Errcode != 0 {
			err = fmt.Errorf(tokenPtr.Errmsg)
			return
		}
		accessToken = tokenPtr.AccessToken
		expired := time.Now().Add(time.Second * time.Duration(tokenPtr.ExpiresIn - 600) )
		s.cacher.SaveMinaAccessToken(accessToken, expired)
	}
	return
}
